<template>
	<view>
		<view class="page__content">
			<z-paging ref="paging" v-model="tableData" @query="queryList" :topZIndex="99999" :bottomZIndex="999999">
				<template #top>
					<up-navbar :fixed="false" title="实验报告" :autoBack="true" :safeAreaInsetTop="true"
						leftIconColor="#fff" style="width: 100%;">
					</up-navbar>

					<view class="page__content__search">
						<up-search :showAction="true" v-model="filterConfig.SearchKey" searchIcon=" " shape="square"
							actionText="搜索" @search="onSearch" @custom="onSearch" :actionStyle="{color:'#fff'}"
							:animation="false">
						</up-search>
					</view>

					<view class="TabsBox">
						<m-scroll-tag @tabChange="changeTab" :tagsList="tabList" bgColor="#52b583">

							<template #right>
								<view class="IconBoxs x-f" @click="openFilter">
									<uni-icons fontFamily="CustomFontPlatform"
										style="margin-left: 14px;font-weight: 600;" color="#818181"
										size="40rpx">{{uni.$utils.toUniCode('&#xe6cb;')}}</uni-icons>
								</view>
							</template>
						</m-scroll-tag>
					</view>

					<!-- 悬浮按钮_新增 -->
					<m-drag-button :isDock="true" :existTabBar="true" :initialBottom="80" @btnClick="addTaskBtn">
						<template #BtnContent>
							<uni-icons type="plusempty" color="#fff" size="50rpx"></uni-icons>
						</template>
					</m-drag-button>
				</template>


				<template v-for="(item, index) in tableData" :key="index">
					<view class="lab-card" @click="innerCellClick(item, index)">
						<!-- 顶部栏 -->
						<view class="lab-card__top">
							<view class="top-left">
								<text class="index">#{{ index + 1 }}</text>
								<text class="bill-no">{{ item.BillNO }}</text>
							</view>
							<text class="bill-date">{{ item.BillDate }}</text>
						</view>

						<!-- 产品信息 -->
						<view class="product-info">
							<text>
								产品：{{ item.ProductCode }} ｜ {{ item.ProductName }} ｜ {{ item.ProductSpec }}
							</text>
							<view class="x-f">
								<view>
									<text>送检数量：</text>
									<text>{{ item.BJNum }}</text>
								</view>
								<view style="margin-left: 20rpx;">
									<text>抽检数量：</text>
									<text>{{ item.CJNum }}</text>
								</view>
							</view>
						</view>

						<!-- 截止日期 -->
						<view v-if="item.TestEndTime" class="deadline-info">
							<text class="deadline-text">截止日期：{{ item.TestEndTime }}</text>
							<text class="deadline-status" :class="{ overdue: item.Delay > 0, normal: item.Delay <= 0 }">
								{{ item.Delay > 0 ? '超期 ' + item.Delay + ' 天' : '剩余 ' + Math.abs(item.Delay) + ' 天' }}
							</text>
						</view>

						<!-- 底部栏 -->
						<view class="card-footer">
							<text>负责人：</text>
							<text class="footer-name">{{ item.CuratorName }}</text>
						</view>

					</view>
				</template>




			</z-paging>
		</view>

		<uni-popup ref="popup_filter" type="right" background-color="#f8f8f8" borderRadius="20px 0 0 20px"
			:is-mask-click="true">
			<view class="popup__content">
				<view :style="{paddingTop: pageConfig.safeTop + 'px'}" style="background-color: #fff;"></view>


				<view class="popup__content__main">
					<!-- 基础信息分组 -->
					<view class="filter-group">
						<view class="filter-title">基础信息</view>

						<!-- 物料信息 -->
						<view class="filter-card">
							<view class="filter-label">物料信息</view>
							<u-input v-model="filterConfig.ProductCode" placeholder="请输入物料信息"
								suffixIcon="edit-pen-fill" />
						</view>

						<!-- 负责人 -->
						<view class="filter-card" @click="openBaseScreen('负责人','check')">
							<view class="filter-label">负责人</view>
							<view class="x-bc">
								<text>{{filterConfig.CuratorName || '请选择负责人'}}</text>
								<uni-icons type="forward" size="20" color="#999" />
							</view>
						</view>
					</view>

					<!-- 时间分组 -->
					<view class="filter-group">
						<view class="filter-title">时间范围</view>

						<!-- 单据日期 -->
						<view class="filter-card">
							<view class="filter-label">单据日期</view>

							<m-date-time mode="module" title="DateTitle" :initData="filterConfig.DropDowmMenu_Date"
								@confirm="onDateConfirm" @reset="onDateReset" :showConfirm="true">
							</m-date-time>
						</view>

						<!-- 截止日期 -->
						<view class="filter-card">
							<view class="filter-label">截止日期</view>
							<view class="x-f">
								<button class="date-btn" @click="openSelectDateTime">
									{{filterConfig.deadlineDate || '点击选择截止日期'}}
								</button>
								<uni-icons type="close" size="30" @click="cleanSelectDate" />
							</view>
						</view>
					</view>

					<!-- 其他条件 -->
					<!-- <view class="filter-group">
						<view class="filter-title">其他条件</view>
						<view class="filter-card">
							<view class="filter-label">是否超时</view>
							<m-radio :options="radioOptions" v-model="filterConfig.Timeout" borderRadius="9999px"
								contentActiveColor="#e1f7f8" contentActiveTextColor="#51d0d0"
								:formtData="{ showText: 'content', hidKey: 'id' }" shape="square" fontSize="14px"
								@change="handleRadioChange" />
						</view>
					</view> -->

				</view>


				<view class="popup__content__bottom">
					<button @click="resetBtn"
						class="popup__content__bottom__btn CommonBtnSize content_bottom_primary_plainBtn">重置</button>
					<button @click="submitBtn"
						class="popup__content__bottom__btn-btn CommonBtnSize content_bottom_primary_Btn">确认</button>
				</view>
			</view>

		</uni-popup>

		<!-- 时间选择器 -->
		<u-datetime-picker :show="showDateTimePicker" v-model="defaultData.choiceTime" mode="date" closeOnClickOverlay
			@confirm="timeChange" @cancel="cancelTimePicker" @close="cancelTimePicker"
			:formatter="formatter"></u-datetime-picker>
	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();


	let pageConfig = reactive<any>({
		safeTop: 0
	})
	pageConfig.safeTop = mainStore.systemConfig.sysDeviceInfo.safeArea.top;

	let filterConfig = reactive<any>({
		SearchKey: "", // 搜索框
		currentIndex: 0, // 单据状态
		ProductCode: "", // 产品信息
		Curator: '', // 负责人
		CuratorData: [], // 负责人
		CuratorName: "",

		Timeout: -1, // 是否超时
		// 时间筛选参数
		DropDowmMenu_Date: {
			DateTitle: "",
			SDate: "",
			EDate: "",
		},
		deadlineDate: "", // 截止日期
	})


	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'labreport_list_choice_' + routes.length
	});
	const openBaseScreen = (str : any, type : any) => {
		switch (type) {
			case 'radio':
			case 'check':

				mainStore.openBaseScreen({
					allowClear: false, // 清除按钮
					cmd: 'XGD_Employee', // 接口名
					titleName: str,
					listeningName: baseScreenListenName.value, // 监听器
					multiple: true, // 是否开启多选
					serverSearch: { // 查询项
						format: { // 数据映射
							displayValue: "EmplName", // 显示值
							hiddenValue: "EmplID", // 隐藏值
							pageIndex: "Pageindex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						searchKey: 'EmplCode', //搜索关键词，应包含在param中
						subText: [{
							label: "编号", // label文本
							labelKey: "EmplCode", // 显示label文本后文字的key
						}],
						choiceData: filterConfig.CuratorData, // 选中数据
						choiceDataKey: "EmplID", // 选中数据的key
					},
					param: { // 传递参数
						EmplCode: '',
						Pageindex: 1,
						PageSize: 30
					}
				});
				break;
			default:
				break;
		}
	}


	const onDateConfirm = (data : any) => {

		const dateObj = {
			SDate: data.start,
			EDate: data.end,
		}
		filterConfig.DropDowmMenu_Date = uni.$utils.deepClone(dateObj)
	}
	// 时间重置
	const onDateReset = () => {

	}

	let defaultData = reactive<any>({
		choiceTime: null
	});
	let showDateTimePicker = ref(false);

	const formatter = (type : any, value : any) => {
		if (type === 'year') {
			return `${value}年`
		}
		if (type === 'month') {
			return `${value}月`
		}
		if (type === 'day') {
			return `${value}日`
		}
		return value
	}

	// 打开时间弹层 -- 截止时间
	const openSelectDateTime = () => {
		let nowTime = new Date();
		if (!uni.$utils.isEmpty(filterConfig.deadlineDate)) {
			nowTime = new Date(filterConfig.deadlineDate);
		};
		defaultData.choiceTime = +nowTime;
		showDateTimePicker.value = true;
	};
	// 清除时间
	const cleanSelectDate = () => {
		filterConfig.deadlineDate = "";
	};

	const timeChange = (data : any) => {
		filterConfig.deadlineDate = uni.$utils.dateFormat(new Date(data.value), 'Y-MM-dd');
		cancelTimePicker();
	};
	const cancelTimePicker = () => {
		showDateTimePicker.value = false;
	}


	const radioOptions = [
		{ content: '全部', id: -1, },
		{ content: '未超时', id: 0, },
		{ content: '超时', id: 1, },
	];
	const handleRadioChange = () => {

	}
	const resetBtn = () => {
		let obj = {
			ProductCode: "", // 产品信息
			Curator: '', // 负责人
			CuratorData: [], // 负责人
			CuratorName: "",

			Timeout: -1, // 是否超时
			// 时间筛选参数
			DropDowmMenu_Date: {
				DateTitle: "",
				SDate: "",
				EDate: "",
			},
			deadlineDate: "", // 截止日期
		};
		Object.assign(filterConfig, obj);
		onSearch();

	}
	const submitBtn = () => {
		popup_filter.value.close();

		onSearch();

	}

	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		setLocalPaging : () => void;
	}
	let paging = ref<pagingInstance | any>(null);

	// 列表数据
	let tableData = ref<any>([]);
	const queryList = (pageNo : number) => {
		uni.$utils.showLoading('正在加载...');

		let param = {
			Approve: -1, // -1全部 0未审核 1已审核
			Curator: filterConfig.Curator, // 负责人
			FSDate: filterConfig.DropDowmMenu_Date.SDate || "", // 开始时间
			FEDate: filterConfig.DropDowmMenu_Date.EDate || "", // 结束时间
			SFJY: filterConfig.currentIndex, // -1全部 0 未检验 1已检验
			BillNO: filterConfig.SearchKey, // 单据编号
			ProductCode: filterConfig.ProductCode, // 物料信息
			TestEndTime: filterConfig.deadlineDate, // 截止日期
			IsDelay: filterConfig.Timeout, // -1全部 0未超时 1超时
			Pageindex: pageNo,
			PageSize: 30,
		};

		request({
			config: {},
			url: 'Qu_LabTestSelectMainForm',
			method: 'POST',
			data: param,
			success: async (ret : any) => {
				console.log(ret);
				if (ret.status == 200) {
					const {
						ds,
						ds2
					} = ret.data;

					// 用 Map 保存映射关系，方便查找
					const dsMap = new Map();

					// 保证顺序一致，构建 result 数组
					const result = ds.map((item : any) => {
						const entry = {
							...item,
							Details: []
						};
						dsMap.set(item.LabTestProductID, entry);
						return entry;
					});

					// 合并 ds2 到对应的 Details 中
					ds2.forEach((detail : any) => {
						const parent = dsMap.get(detail.LabTestProductID);
						if (parent) {
							parent.Details.push(detail);
						}
					});
					// 计算 Delay 字段
					const today = new Date();
					result.forEach((item : any) => {
						if (item.TestEndTime) {
							const endDate = new Date(item.TestEndTime);
							const delay = Math.floor((today - endDate) / (1000 * 60 * 60 * 24)); // 天数差
							item.Delay = delay; // 正数 = 超期，负数 = 剩余
						} else {
							item.Delay = null;
						}
					});


					console.log(result);
					paging.value.complete(result);
					uni.$utils.hideLoading();

				} else {
					paging.value.complete(false);
					uni.$utils.hideLoading();
				}

			},
			fail: (err : any) => {
				paging.value.complete(false);
				uni.$utils.hideLoading();
			}
		})

	};

	const onSearch = () => {
		paging.value.reload();
	};

	let tabList = ref([]);

	// 点击列表项
	const innerCellClick = (data : any, index : number) => {
		uni.navigateTo({
			url: "/st_qms/page_labreport/page_labreport_detail" + "?LabTestProductID=" + data.LabTestProductID
		})
	}
	const changeTab = () => {

	}


	interface filterInterface {
		open : () => void;
		close : () => void;
	};
	let popup_filter = ref<filterInterface | any>(null)
	const openFilter = () => {
		popup_filter.value.open();
	}

	// 新增按钮
	const addTaskBtn = () => {
		uni.navigateTo({
			url: "/st_qms/page_labreport/page_labreport_create"
		})
	}

	onLoad(() => {
		uni.$on("refresh_labreport_list", () => {
			console.log("刷新页面");
			onSearch();
		});

		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			switch (ret.titleName) {
				case "负责人":
					let CuratorArr = [] as any,
						CuratorNameArr = [] as any;

					filterConfig.CuratorData = ret.data;
					ret.data.forEach(({
						EmplID,
						EmplName
					} : any) => {
						CuratorArr.push(EmplID);
						CuratorNameArr.push(EmplName);
					});
					Object.assign(filterConfig, {
						Curator: CuratorArr.join(','),
						CuratorName: CuratorNameArr.join(',')
					});
					break;
				default:
					break;
			}
		})
	});

	onUnload(() => {
		uni.$off("refresh_labreport_list");

		uni.$off(baseScreenListenName.value);
		// 清除选中的模块信息
		qmsStore.orderConfig.order_info = {};
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		&__search {

			.scanQrCode {
				width: 20rpx;
				padding: 5rpx;
			}

			.MenuText {
				font-size: 24rpx;
				border-right: 1px solid #999;
				padding-right: 20rpx;
				margin-right: 8rpx;
			}
		}

		// 顶部tab栏
		.TabsBox {
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-bottom: 2px solid #eee;

			:deep(.u-tabs__wrapper__nav__item__text) {
				padding: 8rpx 20rpx !important;
			}
		}


		.lab-card {
			background-color: #fff;
			border-radius: 20rpx;
			box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.05);
			padding: 24rpx;
			margin: 20rpx 16rpx;
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			border-left: 8rpx solid #4b8df8;
			transition: transform 0.2s;

			&:active {
				transform: scale(0.98);
			}

			.lab-card__top {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.top-left {
					display: flex;
					align-items: center;
					gap: 12rpx;

					.index {
						font-size: 26rpx;
						font-weight: bold;
						color: #4b8df8;
					}

					.bill-no {
						font-size: 28rpx;
						font-weight: 600;
						color: #1f2d3d;
						background-color: #eaf1ff;
						padding: 2rpx 8rpx;
						border-radius: 8rpx;
					}
				}

				.bill-date {
					font-size: 24rpx;
					color: #999;
				}
			}

			.product-info {
				font-size: 24rpx;
				color: #333;
				background-color: #eef4fc;
				padding: 16rpx;
				border-radius: 12rpx;
				display: flex;
				flex-direction: column;
				gap: 6rpx;
				line-height: 1.6;

				.x-f {
					display: flex;
					font-size: 24rpx;
					color: #666;

					view {
						display: flex;
						align-items: center;
					}
				}
			}

			.deadline-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #fffbe8;
				border: 1px dashed #f1c40f;
				padding: 12rpx;
				border-radius: 8rpx;
				font-size: 24rpx;

				.deadline-text {
					color: #7a7a7a;
				}

				.deadline-status {
					font-weight: bold;
				}

				.overdue {
					color: #e74c3c;
				}

				.normal {
					color: #2ecc71;
				}
			}

			.content-list {
				display: flex;
				flex-direction: column;
				gap: 10rpx;
				padding: 12rpx 0;

				.content-row {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.content-text {
						font-size: 24rpx;
						color: #444;
						flex: 1;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.content-icon {
						margin-left: 12rpx;
						opacity: 0.75;
						font-size: 26rpx;
					}
				}
			}

			.card-footer {
				display: flex;
				justify-content: flex-end;
				font-size: 24rpx;
				color: #666;
				border-top: 1px solid #eee;
				padding-top: 10rpx;

				.footer-name {
					font-weight: 600;
					color: #2c3e50;
					margin-left: 6rpx;
				}
			}
		}

	}


	.popup__content {
		height: 100vh;
		max-width: 500px;
		width: 80vw;
		background-color: #f9f9f9;

		&__main {
			.filter-group {
				padding: 0 30rpx;
				margin-bottom: 30rpx;
			}

			.filter-title {
				font-size: 28rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
				color: #333;
			}

			.filter-card {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 24rpx;
				box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
				margin-bottom: 20rpx;
			}

			.filter-label {
				font-size: 26rpx;
				margin-bottom: 12rpx;
				color: #666;
				font-weight: 500;
			}

			.date-btn {
				font-size: 26rpx;
				background-color: #f5f5f5;
				border-radius: 12rpx;
				padding: 10rpx 20rpx;
				flex: 1;
				text-align: left;
			}
		}
	}
</style>